package com.ruoyi.file.service;

import java.io.InputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.nacos.common.utils.IoUtils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.file.config.AliyunOssConfig;
import com.ruoyi.file.utils.FileUploadUtils;

/**
 * 阿里云OSS 文件存储
 *
 * @author ruoyi
 */
@Primary
@Service
public class AliyunOssSysFileServiceImpl implements ISysFileService
{
    @Autowired 
    private AliyunOssConfig aliyunOssConfig;

    @Autowired
    private OSS ossClient;

    /**
     * 阿里云OSS文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file) throws Exception
    {
        InputStream inputStream = null;
        try
        {
            String fileName = FileUploadUtils.extractFilename(file);
            inputStream = file.getInputStream();
            
            // 设置文件元数据
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(file.getSize());
            metadata.setContentType(file.getContentType());
            
            // 上传文件到OSS
            ossClient.putObject(aliyunOssConfig.getBucketName(), fileName, inputStream, metadata);
            
            // 返回访问地址
            return aliyunOssConfig.getDomain() + "/" + fileName;
        }
        catch (Exception e)
        {
            throw new RuntimeException("阿里云OSS上传文件失败", e);
        }
        finally
        {
            IoUtils.closeQuietly(inputStream);
        }
    }

    /**
     * 阿里云OSS文件删除接口
     * 
     * @param fileUrl 文件访问URL
     * @throws Exception
     */
    @Override
    public void deleteFile(String fileUrl) throws Exception
    {
        try
        {
            // 从URL中提取文件名
            String fileName = StringUtils.substringAfter(fileUrl, aliyunOssConfig.getDomain() + "/");
            if (StringUtils.isNotEmpty(fileName))
            {
                ossClient.deleteObject(aliyunOssConfig.getBucketName(), fileName);
            }
        }
        catch (Exception e)
        {
            throw new RuntimeException("阿里云OSS删除文件失败", e);
        }
    }
}
